<template>
  <teleport to="body">
    <div v-if="visible" class="hand-drawn-confirm-overlay" @click="handleOverlayClick">
      <div class="hand-drawn-confirm-container" @click.stop>
        <div class="hand-drawn-confirm-card" ref="cardRef">
          <!-- 手绘边框 SVG -->
          <svg
            class="hand-drawn-border"
            :width="svgWidth"
            :height="svgHeight"
            xmlns="http://www.w3.org/2000/svg"
            ref="svgRef"
          >
            <path
              :d="borderPath"
              fill="none"
              stroke="#333"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>

          <!-- 对话框内容 -->
          <div class="confirm-content">
            <!-- 标题 -->
            <h3 class="confirm-title">{{ title }}</h3>

            <!-- 消息 -->
            <p class="confirm-message">{{ message }}</p>

            <!-- 按钮组 -->
            <div class="confirm-buttons">
              <HandDrawnCard
                variant="secondary"
                size="small"
                @click="handleCancel"
                class="cancel-btn"
              >
                {{ cancelButtonText }}
              </HandDrawnCard>

              <HandDrawnCard
                :variant="confirmVariant"
                size="small"
                @click="handleConfirm"
                class="confirm-btn"
              >
                {{ confirmButtonText }}
              </HandDrawnCard>
            </div>
          </div>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, onMounted, onUnmounted, watch, toRefs } from "vue";
import {
  Warning,
  QuestionFilled,
  CircleCheckFilled,
  CircleCloseFilled,
  InfoFilled,
} from "@element-plus/icons-vue";
import HandDrawnCard from "./HandDrawnCard.vue";
import rough from "roughjs";

interface Props {
  visible?: boolean;
  type?: "warning" | "info" | "success" | "error" | "question";
  title?: string;
  message?: string;
  confirmButtonText?: string;
  cancelButtonText?: string;
  closeOnClickModal?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  type: "warning",
  title: "确认操作",
  message: "您确定要执行此操作吗？",
  confirmButtonText: "确定",
  cancelButtonText: "取消",
  closeOnClickModal: true,
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  confirm: [];
  cancel: [];
}>();

const cardRef = ref<HTMLElement>();
const svgRef = ref<SVGSVGElement>();
const svgWidth = ref(400);
const svgHeight = ref(280);
const borderPath = ref("");

// 根据类型确定图标和样式
const iconComponent = computed(() => {
  const iconMap = {
    warning: Warning,
    question: QuestionFilled,
    success: CircleCheckFilled,
    error: CircleCloseFilled,
    info: InfoFilled,
  };
  return iconMap[props.type];
});

const iconColor = computed(() => {
  const colorMap = {
    warning: "#e6a23c",
    question: "#409eff",
    success: "#67c23a",
    error: "#f56c6c",
    info: "#909399",
  };
  return colorMap[props.type];
});

const confirmVariant = computed(() => {
  if (props.type === "error" || props.type === "warning") {
    return "accent";
  }
  return "primary";
});

// 更新SVG尺寸
const updateSvgSize = () => {
  if (!cardRef.value) return;

  const borderOverflow = 8;
  const width = cardRef.value.offsetWidth + borderOverflow * 2;
  const height = cardRef.value.offsetHeight + borderOverflow * 2;

  svgWidth.value = width;
  svgHeight.value = height;
};

// 绘制手绘边框
const drawHandDrawnBorder = () => {
  if (!svgRef.value || svgWidth.value === 0 || svgHeight.value === 0) {
    console.log(
      "SVG ref or size not available:",
      !!svgRef.value,
      svgWidth.value,
      svgHeight.value
    );
    return;
  }

  const svg = svgRef.value;

  try {
    const rc = rough.svg(svg);

    // 清除之前的路径
    svg.innerHTML = "";

    const padding = 4;
    const width = svgWidth.value - padding * 2;
    const height = svgHeight.value - padding * 2;

    if (width <= 0 || height <= 0) {
      console.log("Invalid dimensions:", width, height);
      return;
    }

    // 绘制手绘矩形
    const rect = rc.rectangle(padding, padding, width, height, {
      roughness: 1.2,
      bowing: 0.5,
      stroke: "#333",
      strokeWidth: 2,
      seed: 1,
      fill: "none",
    });

    svg.appendChild(rect);
    console.log("Hand-drawn border created successfully");

    // 获取生成的路径
    const path = rect.querySelector("path");
    if (path) {
      borderPath.value = path.getAttribute("d") || "";
    }
  } catch (error) {
    console.error("Error drawing hand-drawn border:", error);
  }
};

// 初始化边框
const initializeBorder = () => {
  if (!cardRef.value) {
    console.log("Card ref not available, retrying...");
    setTimeout(() => {
      initializeBorder();
    }, 50);
    return;
  }

  updateSvgSize();
  nextTick(() => {
    drawHandDrawnBorder();
    console.log("Border initialized, SVG size:", svgWidth.value, "x", svgHeight.value);
  });
};

// 处理函数
const handleConfirm = () => {
  emit("confirm");
  emit("update:visible", false);
};

const handleCancel = () => {
  emit("cancel");
  emit("update:visible", false);
};

const handleOverlayClick = () => {
  if (props.closeOnClickModal) {
    handleCancel();
  }
};

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === "Escape") {
    handleCancel();
  } else if (event.key === "Enter") {
    handleConfirm();
  }
};

// 监听visible变化
const { visible } = toRefs(props);
watch(visible, (newVisible: boolean) => {
  if (newVisible) {
    nextTick(() => {
      initializeBorder();
      document.addEventListener("keydown", handleKeydown);

      // 启动ResizeObserver
      if (cardRef.value) {
        observer.observe(cardRef.value);
      }
    });
  } else {
    document.removeEventListener("keydown", handleKeydown);
    observer.disconnect();
  }
});

onMounted(() => {
  if (props.visible) {
    nextTick(() => {
      initializeBorder();
      document.addEventListener("keydown", handleKeydown);

      // 启动ResizeObserver
      if (cardRef.value) {
        observer.observe(cardRef.value);
      }
    });
  }
});

onUnmounted(() => {
  document.removeEventListener("keydown", handleKeydown);
  observer.disconnect();
});

// 监听尺寸变化
const observer = new ResizeObserver(() => {
  if (props.visible && cardRef.value) {
    nextTick(() => {
      updateSvgSize();
      drawHandDrawnBorder();
    });
  }
});

// 暴露方法
defineExpose({
  initializeBorder,
});
</script>

<style lang="scss" scoped>
.hand-drawn-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
  backdrop-filter: blur(2px);
  animation: fadeIn 0.2s ease-out;
}

.hand-drawn-confirm-container {
  padding: 20px;
  max-width: 90vw;
  max-height: 90vh;
  animation: zoomIn 0.3s ease-out;
}

.hand-drawn-confirm-card {
  position: relative;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  min-width: 320px;
  max-width: 500px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.hand-drawn-border {
  position: absolute;
  top: -4px;
  left: -4px;
  pointer-events: none;
  z-index: 1;
}

.confirm-content {
  position: relative;
  z-index: 2;
  padding: 30px 25px 25px;
  text-align: center;
}

.confirm-icon {
  margin-bottom: 20px;
  animation: bounceIn 0.4s ease-out 0.1s both;
}

.confirm-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px 0;
  line-height: 1.4;
}

.confirm-message {
  font-size: 14px;
  color: #666;
  margin: 0 0 25px 0;
  line-height: 1.5;
  word-break: break-all;
}

.confirm-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;

  .cancel-btn,
  .confirm-btn {
    min-width: 80px;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-2px);
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes zoomIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes bounceIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.8);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

// 移动端适配
@media (max-width: 768px) {
  .hand-drawn-confirm-container {
    padding: 15px;
  }

  .hand-drawn-confirm-card {
    min-width: 280px;
  }

  .confirm-content {
    padding: 25px 20px 20px;
  }

  .confirm-title {
    font-size: 16px;
  }

  .confirm-message {
    font-size: 13px;
  }

  .confirm-buttons {
    gap: 8px;

    .cancel-btn,
    .confirm-btn {
      min-width: 70px;
    }
  }
}
</style>
